<?php

session_start();

error_reporting(E_ALL);
ini_set('display_errors', '1');

require 'google-api-php-client-master/autoload.php';

$client_id = '1097530924560-9dv7lmvrmlfsdrn3rbd8a197ci34n4og.apps.googleusercontent.com';
$client_secret = 'VMTuLVpXMyjbdi_EoyeJxUnr';
$redirect_uri = 'http://www.bytefact.com/mesbagapi.php';

$client = new Google_Client();

$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
//$client->setAccessType('offline');

$client->addScope("https://mail.google.com");


$service = new Google_Service_Gmail($client);


if (isset($_REQUEST['logout'])) { // logout: destroy token
    unset($_SESSION['access_token']);
}



if (isset($_GET['code'])) { // we received the positive auth callback, get the token and store it in session
    $client->authenticate($_GET['code']);
    $_SESSION['access_token'] = $client->getAccessToken();
    $url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    header('Location: ' . filter_var($url, FILTER_VALIDATE_URL));
}

if (isset($_SESSION['access_token'])) { // extract token from session and configure client
    $client->setAccessToken($_SESSION['access_token']);
    //var_dump($client);
    //echo "<pre>" . $client->getAccessToken() . "</pre>";  
} else {
    $loginUrl = $client->createAuthUrl();
    echo 'Click <a href="' . $loginUrl . '">here</a> to login';
	header('Location: ' . filter_var($loginUrl, FILTER_VALIDATE_URL));
}

echo $client->getAccessToken();

if( isset($_SESSION['access_token']) && $client->getAccessToken() ){
  echo "WORKED";
  }


  $optParams = array('q' => 'is:unread');
  $messages = $service->users_messages->listUsersMessages('mesba.cit06@gmail.com',$optParams);
  echo "<pre>", var_dump($messages['modelData']['messages']) , "</pre>";
  echo "<pre>", var_dump($messages) , "</pre>";

  
  /*
  
  $optParams = array();
  $optParams['format'] = 'metadata';
  $optParams['metadataHeaders'] = array('To','From','Message-ID','Subject');
  $messages = $service->users_messages->get('mesba.cit06@gmail.com', '14b33f907cc6e3c6', $optParams);
  echo "<pre>", var_dump($messages['modelData']['payload']['headers']) , "</pre>";
  echo json_encode($messages['modelData']['payload']['headers']);
  //$mj = json_encode($messages['modelData']['payload']['headers']);
  //$mj = json_decode($mj);
  echo "<br/>";
  //echo $mj[1]->value; //$to = $mail->to ;
  
  $obj = (object) array('to'=> '', 'from'=>'', 'subject'=>'', 'message_id'=> '');
  $mj = $messages['modelData']['payload']['headers'];
  foreach ($mj as $m){
        if($m['name'] == 'To') $obj->to = $m['value'];
        if($m['name'] == 'From') $obj->from = $m['value'];
        if($m['name'] == 'Subject') $obj->subject = $m['value'];
        if($m['name'] == 'Message-ID') $obj->message_id = $m['value'];
  }
  
  var_dump($obj);
 
    
  */
  //$obj = (object) array('foo' => 'bar', 'property' => 'value');
  
//  foreach($mj as $m){
//    echo $m->Subject;
//    echo $m['Subject'];
//  }
  
  
  //echo $mj->Subject;
  //echo $mj->To;
  
  //$postbody = new Google_Service_Gmail_ModifyThreadRequest;
  //$postbody->setRemoveLabelIds(array('UNREAD'));
  //$messages = $service->users_threads->modify('info.bytefact@gmail.com', '14b21d7f598a667c',$postbody);

  
  /*
  
  try {
  
  require_once 'lib/class.phpmailer.php';

  $messages = array('hey there', 'how are you', 'my name is natasha', 'tangail chude ja', 'hoga mara kha');
  $address = array('mesba.bd@gmail.com','riyadh.iut@gmail.com','mesba.cit06@hotmail.com','gonzalezshopia@gmail.com','mesba.cit06@yahoo.com');
  $subject = array( 'how are you',  'tangail chude ja', 'hoga mara kha','hey there', 'my name is natasha');
  

for($i=0;$i<1;$i++){



$mail = new PHPMailer();
$mail->CharSet = "UTF-8";
//$subject = "my subject";
$msg = $messages[$i%5];
echo $msg;
$from = "mesba.cit06@gmail.com";
$fname = "my name";
$mail->From = $from;
$mail->FromName = $fname;
$mail->AddAddress($address[$i%5]);
$mail->AddReplyTo($from,$fname);
$mail->Subject = $subject[$i%5];
$mail->Body    = $msg;
$mail->preSend();
$mime = $mail->getSentMIMEMessage();
$m = new Google_Service_Gmail_Message();
$data = base64_encode($mime);
$data = str_replace(array('+','/','='),array('-','_',''),$data); // url safe
$m->setRaw($data);

$ret = $service->users_messages->send('me', $m);

echo "</br>";echo "</br>";
if(!isset($ret)) echo "######### ret not set !!!";
echo "</br>";echo "</br>";
echo "mail send returns :";
echo "</br>";
var_dump($ret);
echo "</br>";echo "</br>";
echo "message id : " .$ret['id'];


}
  }
  catch(Exception $e){
	$e->getMessage();
  }
  */
  
  //var_dump($messages);



/*

//try {
    if (
    
    isset($_SESSION['access_token']) 
    
    && $client->getAccessToken()
    
    ) { // auth call to google
        //$messages = $service->users_messages->listUsersMessages('me', ['maxResults' => 2, 'labelIds' => 'INBOX']);
        //ar_dump($messages);
        echo "try"
    }
    else {
      echo "else try";
    }
//}
//catch (Google_Auth_Exception $e)
//{
  //echo 'Looks like your access token has expired. click here to login <a href="' . $loginUrl . '">here</a> to login';
 // echo "catch";

//}
*/
?>
